package com.lagou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

@Component
public class FastDFSClientService {

    @Autowired
    private FastFileStorageClient  fastFileStorageClient;

    /**
     * 文件上传
     * @param bytes 文件数据
     * @param fileSize 文件大小
     * @param extension 拓展名
     * @return 存储路径
     */
    public String  uploadFile(byte[] bytes,long fileSize,String extension){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        //元数据可写可不写，暂时设置为空
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream,fileSize,extension,null);
        System.out.println(storePath.getGroup() + ":" + storePath.getPath() + ":"+storePath.getFullPath());
        return  storePath.getFullPath();
    }

    /**
     * 文件下载
     * @param fileUrl 文件路径
     * @return 文件数据
     */
    public  byte[] downloadFile(String fileUrl){
        //返回的路径格式:  group1/M00/00/00/wKgBBl9QSMWAA7YCAAuz9EnVKDI559.jpg
        String group = fileUrl.substring(0,fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/")+1);
        //不用这个是无法进行下载的
        DownloadByteArray  downloadByteArray = new DownloadByteArray();
        byte[] bytes  = fastFileStorageClient.downloadFile(group,path,downloadByteArray);
        return   bytes;
    }
}
